<?php
/**
 * Created by PhpStorm.
 * User: boye009
 * Date: 2016/4/7
 * Time: 15:31
 */

namespace Shop\Api;

use Common\Api\Api;
use Shop\Model\ProductPropModel;

class ProductPropApi extends Api{

    /**
     * 添加
     */
    const ADD = "Shop/ProductProp/add";
    /**
     * 保存
     */
    const SAVE = "Shop/ProductProp/save";
    /**
     * 查询一条数据
     */
    const GET_INFO = "Shop/ProductProp/getInfo";

    /**
     * 查询，不分页
     */
    const QUERY_NO_PAGING = "Shop/ProductProp/queryNoPaging";


    const GET_PROP_BY_PID = "Shop/ProductProp/getPropByPid";

    /**
     * 批量修改商品属性
     */
    const EDIT_PROPS = "Shop/ProductProp/editProps";

    protected function _init(){
        $this -> model = new ProductPropModel();
    }

    /**
     * 返回json格式
     * @param $pid
     */
    public function getPropByPid($pid){
        $map = array(
            'pid' => $pid,
        );
        $result = $this -> model -> where($map) -> field('prop_id,id') -> select();
        if($result === false){
            $error = $this -> model -> getDbError();
            return $this -> apiReturnErr($error);
        }
        $arr = array();
        foreach($result as $vo){
            array_push($arr,array('id'=>$vo['prop_id'],'vid'=>$vo['id']));
        }
        return $this -> apiReturnSuc(json_encode($arr));
    }

    /**
     * 批量修改商品属性
     * @param $pid
     * @param $prop_value_ids
     */
    public function editProps($pid,$props){
        //首先删除所有商品属性
        $this->model->startTrans();
        $map = [
            'pid' => $pid
        ];
        $r = $this->delete($map);

        $dataList = [];
        foreach ($props as $val){
            $dataList[] = [
                'pid' => $pid,
                'prop_id' => $val['prop_id'],
                'value_id' => $val['value_id'],
                'value_name' => $val['value_name']
            ];
        }

        $y = $this->model->addAll($dataList);

        if($r['status']===true && $y!==false){
            $this->model->commit();
            return $this->apiReturnSuc('修改成功');
        }else{
            $this->model->rollback();
            return $this->apiReturnErr('修改失败');
        }
    }

}